/* eslint-disable no-async-promise-executor */
import {
  getNewCartGoods,
  reqMergeLocalCart,
  reqFindCartList,
  reqInsertCart,
  reqDeleteCart,
  reqUpdateCartSku,
  reqCheckAllCart
} from '@/api/cart'
export default {
  namespaced: true,
  state: () => {
    return {
      list: []
    }
  },
  mutations: {
    insertCart (state, goods) {
      console.log(goods, 888)
      // alert(11)
      // 添加购物车逻辑
      // 加入购物车逻辑
      const sameIndex = state.list.findIndex(
        (item) => item.skuId === goods.skuId
      )

      if (sameIndex >= 0) {
        alert(sameIndex)
        //  表示购物车中有这件商品需要数量叠加
        state.list[sameIndex].count = state.list[sameIndex].count + goods.count
      } else {
        //  alert(sameIndex)
        //  表示购物车中没有这件商品，直接添加
        state.list.unshift(goods)
      }
    },
    deleteCart (state, goods) {
      const index = state.list.findIndex((item) => item.skuId === goods.skuId)
      state.list.splice(index, 1)
    },
    updateCart (state, goods) {
      console.log(goods, 887755)
      var sku = state.list.find((item) => item.skuId === goods.skuId)
      sku.isEffective = goods.isEffective
      sku.nowPrice = goods.nowPrice
      sku.stock = goods.stock
    },
    singleCheck (state, { goods, selected }) {
      const curItem = state.list.find((item) => item.skuId === goods.skuId)
      curItem.selected = selected
    },
    checkEffectAll (state, selected) {
      state.list.forEach((item) => {
        if (item.isEffective) {
          item.selected = selected
        }
      })
    },
    // 数量修改mutation
    changeCount (state, { goods, count }) {
      const item = state.list.find((item) => item.skuId === goods.skuId)
      item.count = count
    },
    // 设置list的mutation
    setList (state, newList) {
      state.list = newList
    }
  },
  actions: {
    asyncInsertCart (context, goods) {
      // alert(222)
      return new Promise(async (resolve, reject) => {
        // 区分登录 和 未登陆的状态
        // 已登录
        if (context.rootState.user.profile.token) {
          // 已登录，发请求 - 异步
          const { skuId, count } = goods
          await reqInsertCart({ skuId, count })
          await context.dispatch('asyncUpdateCart')
        } else {
          // 非登录
          context.commit('insertCart', goods)
          resolve()
        }
      })
    },
    asyncDeleteCart (context, goods) {
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录的删除
          await reqDeleteCart([goods.skuId])
          await context.dispatch('asyncUpdateCart')
        } else {
          // 未登陆
          context.commit('deleteCart', goods)
          resolve()
        }
      })
    },
    asyncUpdateCart (context) {
      // 发送请求，更新购物车中所有的商品信息
      return new Promise((resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 登录了
          // TODO
          // console.log('已登录，发请求 - 异步操作')
          reqFindCartList().then((res) => {
            context.commit('setList', res.result)
            resolve()
          })
        } else {
          // 没有登录，需要发送请求进行商品信息更新
          const requestArr = context.state.list.map((item) => {
            return getNewCartGoods(item.skuId)
          })
          console.log(requestArr, 77)
          Promise.all(requestArr).then((res) => {
            console.log(res, 8811)
            res.forEach((item, index) => {
              context.commit('updateCart', {
                skuId: context.state.list[index].skuId,
                ...item.result
              })
            })
            resolve()
          })
        }
      })
    },
    asyncSingleCheck (context, { goods, selected }) {
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录 TODO
          await reqUpdateCartSku({
            skuId: goods.skuId,
            selected: selected
          })
          await context.dispatch('asyncUpdateCart')
        } else {
          // 未登录 把商品信息加入本地vuex中
          context.commit('singleCheck', { goods, selected })
          resolve()
        }
      })
    },
    asyncCheckEffectAll (context, selected) {
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录 TODO
          const skuIds = context.getters.effectiveList.map((item) => item.skuId)
          await reqCheckAllCart({ selected: selected, ids: skuIds })
          await context.dispatch('asyncUpdateCart')
        } else {
          // 未登录
          context.commit('checkEffectAll', selected)
          resolve()
        }
      })
    },
    // 修改数量action
    asyncChangeCount (context, { goods, count }) {
      return new Promise(async (resolve, reject) => {
        if (context.rootState.user.profile.token) {
          // 已登录，发请求 - 异步
          await reqUpdateCartSku({
            skuId: goods.skuId,
            count: count
          })
          await context.dispatch('asyncUpdateCart')
        } else {
          context.commit('changeCount', { goods, count })
          resolve()
        }
      })
    },
    async asyncMergeLocalCart (context) {
      const cartList = context.state.list.map(({ skuId, selected, count }) => {
        return { skuId, selected, count }
      })
      await reqMergeLocalCart(cartList)
      // 合并成功后，从后端获取最新购物车列表替换本地
      // console.log('需要合并购物车数据')
      await context.dispatch('asyncUpdateCart')
    }
  },
  getters: {
    // 计算有效商品列表 isEffective = true  filter
    effectiveList (state) {
      return state.list.filter((item) => item.stock > 0 && item.isEffective)
    },
    // 有效商品总数量 把effctiveList中的每一项的count叠加起来
    effectiveTotal (state, getters) {
      return getters.effectiveList.reduce((sum, item) => sum + item.count, 0)
    },
    // 总钱数  = 所有单项的钱数累加  单项的钱数 = 数量 * 单价
    effectiveTotalPrice (state, getters) {
      return getters.effectiveList
        .reduce((sum, item) => sum + item.count * item.nowPrice, 0)
        .toFixed(2)
    },
    // 无效商品列表
    ineffectiveList (state) {
      return state.list.filter((item) => !(item.stock > 0 && item.isEffective))
    },
    // 已选择的列表
    selectedList (state, getters) {
      return getters.effectiveList.filter((item) => item.selected)
    },
    // 已选择的商品总数
    selectedAllCounts (state, getters) {
      return getters.selectedList.reduce((sum, item) => sum + item.count, 0)
    },
    // 已选择的列表总价
    selectedAllPrice (state, getters) {
      return getters.selectedList
        .reduce((sum, item) => sum + item.count * item.nowPrice, 0)
        .toFixed(2)
    },
    // 是否全部选中
    isAllEffectSelected (state, getters) {
      return (
        getters.effectiveList.length === getters.selectedList.length &&
        getters.selectedList.length !== 0
      )
    }
  }
}
